package com.qc31.baselib.base

import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.viewbinding.ViewBinding
import autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.qc31.baselib.custom.MLoadingDialog
import com.qc31.baselib.entity.ToastEntity
import com.qc31.baselib.utils.toast

/** @Author Jasper @Time 2020/7/17 @Desc 懒加载Fragment */
abstract class LazyLoadSirFragment<VB : ViewBinding>(
    private val inflater: (LayoutInflater, ViewGroup?, Boolean) -> VB
) : Fragment() {
    private var _binding: VB? = null
    protected val binding: VB get() = _binding!!
    protected lateinit var loadService: LoadService<Any>

    private var isFirstLoad = true // 是否第一次加载
    protected val scopeProvider: AndroidLifecycleScopeProvider by lazy {
        AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = inflater(layoutInflater, container, false)
        loadService = LoadSir.getDefault().register(binding.root) { onNetReload(it) }
        return loadService.loadLayout
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(view)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        isFirstLoad = true
        _binding = null
    }

    override fun onResume() {
        super.onResume()
        if (isFirstLoad) {
            // 将数据加载逻辑放到onResume()方法中
            initData()
            initEvent()
            isFirstLoad = false
        }
    }


    /**
     * 初始化视图
     *
     * @param view
     */
    abstract fun initView(view: View)

    /** 初始化数据 */
    abstract fun initData()

    /** 初始化事件 */
    abstract fun initEvent()

    protected open fun onNetReload(v: View) {}
    protected fun isShowLoading(isShow: Boolean) {
        if (isShow) MLoadingDialog.showLoading(activity as Activity) else MLoadingDialog.dismiss()
    }

    protected fun showToast(messageId: Int) {
        showToast(getString(messageId))
    }

    protected fun showToast(message: String) {
        requireActivity().toast(message)
    }

    fun toastObserver(entity: ToastEntity) {
        if (entity.toast.isNotEmpty()) {
            requireActivity().toast(entity.toast)
            return
        }
        if (entity.toastId != 0) {
            requireActivity().toast(entity.toastId)
            return
        }
        isShowLoading(entity.isShowLoading)
    }

}